<template>
  <div>
    <van-nav-bar
      title="搜索"
      left-arrow
      @click-left="$router.back()"
    />
    <van-search
      v-model.trim="keyword"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="inputFn"
      @search="search(keyword)"
    >
      <template #action>
        <div @click="search(keyword)">搜索</div>
      </template>
    </van-search>
    <!-- 搜索推荐 -->
    <van-cell-group v-if="keyword">
      <van-cell icon="search" v-for="(item,index) in list" :key="index">
        <template #title>
          <div class="title" v-html="high(item)" @click="search(item)"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录" />
      <van-cell :title="item" v-for="(item,index) in historyList" :key="index" @click="search(item)">
        <van-icon name="cross" @click.stop="del(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSearchSugges } from '@/api/search'
import { getHistory, setHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '',
      list: [],
      historyList: getHistory()
    }
  },
  methods: {
    // 优化后防抖发送请求
    inputFn () {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (!this.keyword) return this.$toast('不能为空')
        const res = await getSearchSugges(this.keyword)
        this.list = res.data.options
      }, 500)
    },
    // 关键字在搜索推荐列表处高亮
    high (str) {
      const reg = new RegExp(this.keyword, 'gi')
      return str.replace(reg, function (key) {
        return `<span style='color:red'>${key}</span>`
      })
    },
    // 注册事件，触发跳转到搜索结果页并且将关键字存到历史记录中
    search (keyword) {
      if (!keyword) return this.$toast('请输入关键字')
      this.historyList = this.historyList.filter(item => item !== keyword)
      this.historyList.unshift(keyword)
      setHistory(this.historyList)
      this.$router.push({
        path: '/search/result',
        query: {
          keyword
        }
      })
    },
    del (key) {
      this.historyList = this.historyList.filter(item => item !== key)
      setHistory(this.historyList)
    }
  }
}
</script>

<style>

</style>
